package com.bbgwap.controller;

import com.bbgwap.model.WXModel.TextMessage;
import com.bbgwap.utils.MessageUtils;
import com.bbgwap.utils.message.MessageHandler;
import org.aspectj.bridge.MessageUtil;
import org.dom4j.DocumentException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

import static com.bbgwap.base.APPCONST.CHARSET;
import static com.bbgwap.base.APPCONST.CHARSET_XML;

/**
 * Created by lixiang on 18/04/2017.
 */
@Controller
public class WXValidataController extends BaseController{


    @RequestMapping(value = {"wx"}, method = RequestMethod.GET, produces = CHARSET)
    public void showPage(@RequestParam(value = "echostr", required = false) String echostr, PrintWriter out) {
        if (echostr != null) {
            logger.info("来自微信服务器的请求：" + echostr);
            out.print(echostr);
        } else {
            logger.info("来自微信服务器的请求为空");
        }
        out.flush();
        out.close();
    }
    @RequestMapping(value = {"wx"}, method = RequestMethod.POST)
    public void getMessage(HttpServletRequest request,
                           HttpServletResponse response
                           )  {
        response.setContentType("text/html;charset=utf-8"); //设置输出编码格式
        System.out.println("请求进入");
        String result = "";
        try {
            Map map = MessageHandler.parseXml(request);
            System.out.println("开始构造消息");
            result = MessageHandler.buildXml(map, response);
            System.out.println(result);
            if(result.equals(""))
                result = "未正确响应";
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("发生异常："+ e.getMessage());
        }
        try {
            response.getWriter().println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
